// qt includes
#include <QAudioOutput>
#include <QBuffer>
#include <QAudioFormat>
#include <QBuffer>
#include <QByteArray>
#include <QAudioDeviceInfo>

// std includes
#include <cmath>
#include <iostream>

// dosgame includes
#include "qt_sound.h"

SoundSystem::SoundSystem(int freq, int duration)
{
    m_format = new QAudioFormat();

    m_format->setChannelCount(2);
    m_format->setSampleRate(44100);
    m_format->setSampleSize(8);
    m_format->setSampleType(QAudioFormat::SignedInt);
    m_format->setCodec("audio/pcm");

    m_audioOutput = new QAudioOutput(*m_format);

    m_byteArray = new QByteArray(m_format->sampleRate() * duration * 2, 0);

    int size = m_byteArray->size();

    // initialize the buffer: 440 Hz = A above middle C
    for (int i = 0; i < size/2; ++i) {
        double arg = 2.0 * i * 3.14159265 * freq / m_format->sampleRate();
        (*m_byteArray)[2*i] = (char)(127.0 * std::sin(arg/880.0)*std::sin(arg));
        (*m_byteArray)[2*i+1] = (char)(127.0 * std::cos(arg/880.0)*std::sin(arg));
    }

    m_buffer = new QBuffer(m_byteArray);
    m_audioOutput->start(m_buffer);

    if ( !m_buffer->isOpen())
        m_buffer->open(QIODevice::ReadOnly);

    if ( m_audioOutput->error() != QAudio::NoError) {
        std::cout << "ERROR: " << m_audioOutput->error() << std::endl;
    }


    // testin
    QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();

    std::cout << "device name " << deviceInfo.deviceName().toStdString() << std::endl;
    std::cout << "supported channel counts ";

    for ( auto i : deviceInfo.supportedChannelCounts())
        std::cout << i << " ";

    std::cout << std::endl;

}

SoundSystem::~SoundSystem()
{
    delete m_audioOutput;
    delete m_format;
    delete m_buffer;
    delete m_byteArray;
}
